package com.example.review;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class chapterFive3Activity extends AppCompatActivity {
    private IntentFilter intentFilter;
    private LocalReceiver localReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chapter_five3);
        //获取实例
        localBroadcastManager=LocalBroadcastManager.getInstance(this);
        Button button=findViewById(R.id.sendLocal);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent("com.example.review.LOCAL_BROADCAST");
                //通过localBroadcastManager发送本地广播
                localBroadcastManager.sendBroadcast(intent);

            }
        });

        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("com.example.review.LOCAL_BROADCAST");
        LocalReceiver localReceiver=new LocalReceiver();
        //通过localBroadcastManager注册本地广播监听器
        localBroadcastManager.registerReceiver(localReceiver,intentFilter);
    }

    /**
     * 动态注册一定记得取消注册
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册
        localBroadcastManager.unregisterReceiver(localReceiver);
    }


    class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "received local broadcast", Toast.LENGTH_SHORT). show();
        }
    }
}